// 导入数据库连接对象
const db = require("../db");
// 导入配置信息
const { debug, info, token } = require("../config");
// 导入bcryptjs进行用户密码的加密
const bcrypt = require("bcryptjs");
// 导入生成token字符串的包
const jwt = require("jsonwebtoken");

/**
 * 用户注册函数
 */
exports.regUser = async (req, res) => {
  // 接收表单数据
  const userinfo = req.body;
  // 判断数据是否合法
  // 定义sql语句
  let sql = `select * from blog_user where username="${userinfo.username}"`;
  // 执行sql语句并根据结果判断用户名是否被占用
  const [rows] = await db.promise().query(sql);
  // 用户名被占用
  if (rows.length > 0) {
    return res.send(info(1, "用户名被占用，请更换其他用户名", ""));
  }
  // TODO 用户名可用，就继续下面步骤
  // 调用bcrypt.hashSync(明文密码,随机盐的长度)对用户密码加密处理
  /* 1.加密之后的密码，无法被逆向破解
  2.同一明文密码多次加密，得到的加密结果各不相同，保证了安全性    */
  // console.log(userinfo)
  userinfo.password = bcrypt.hashSync(userinfo.password, 10);

  // 定义插入用户的sql语句
  sql = `insert into blog_user (username,nickname,password) values("${userinfo.username}","${userinfo.nickname}","${userinfo.password}")`;
  const [result] = await db.promise().query(sql);
  // 判断sql语句执行是否成功
  if (result.affectedRows !== 1) {
    return res.cc("注册用户失败，请稍后重试");
  }
  res.send(info(0, "注册成功！", ""));
};
/**
 * 用户处理函数
 * 登录
 */
exports.login = async (req, res) => {
  const { username, password, ip, address, flag } = req.body;
  // console.log(ip, address);
  const sql = `select * from blog_user where username="${username}"`;
  try {
    var [rows] = await db.promise().query(sql);
    if (rows.length !== 1) {
      return res.send(info(1, "该账户不存在", ""));
    }
    if (flag !== 0) {
      if (rows[0].role == "用户") {
        return res.send(info(1, "该账户不是管理员", ""));
      }
    }
    if (rows[0].state == 1) {
      return res.send(info(1, "该账户已禁用", ""));
    }
    // 确定存在后，判断密码是否正确
    const compareResult = bcrypt.compareSync(password, rows[0].password);
    if (!compareResult) {
      if (password != rows[0].password) {
        return res.send(info(1, "登录密码错误", ""));
      }
    }
    const sql1 = `update blog_user set ip="${ip}",address="${address}",loginTime=NOW() where id=${rows[0].id}`;
    const [result] = await db.promise().query(sql1);
  } catch (error) {
    res.send(info(1, "mysql错误", debug ? error : ""));
  }
  // 生成token字符串
  const user = { ...rows[0], password: "", avatar: "" };
  const tokenStr = jwt.sign(user, token.jwtSecretKey, {
    expiresIn: token.expiresIn,
  });
  /**
   * 挂载token,发送到客户端
   */
  // 设置响应头
  res.setHeader("Access-Control-Expose-Headers", "Authorization");
  // 挂载token
  res.header("Authorization", tokenStr);
  res.send(info(0, "登录成功", { ...user, tokenStr }));
};

/**
 * 修改密码的处理函数
 */
exports.updatePwd = async (req, res) => {
  const id = req.params.id;
  const { oldPwd, newPwd } = req.body;
  // 查询user
  let sql = `select * from blog_user where id="${id}"`;
  const [rows] = await db.promise().query(sql);
  if (rows.length != 1) {
    res.send(info(1, "该管理员不存在", ""));
  }
  // 判断旧密码是否正确
  const compareResult = bcrypt.compareSync(oldPwd, rows[0].password);
  if (!compareResult) {
    if (oldPwd != rows[0].password) {
      return res.send(info(1, "旧密码错误", ""));
    }
  }
  // 对新密码加密
  const newPwd_1 = bcrypt.hashSync(newPwd, 10);
  // 更新数据库的旧密码
  sql = `update blog_user set password="${newPwd_1}" where id="${id}"`;
  const [result] = await db.promise().query(sql);
  // console.log(result.affectedRows);
  if (result.affectedRows == 1) {
    res.send(info(0, "更新密码成功", ""));
  }
};

/**
 * 获取头像
 */
exports.getAvatar = async (req, res) => {
  const id = req.params.id;
  const sql = `select id,username,avatar from blog_user where id=${id}`;
  try {
    const [rows] = await db.promise().query(sql);
    if (rows) {
      res.send(info(0, "获取成功", rows[0]));
    }
  } catch (error) {
    res.send(info(1, "数据库执行错误", debug ? error : ""));
  }
};

/**
 * 修改头像
 */
exports.uploadPic = async (req, res) => {
  const id = req.params.id;
  // 头像路径
  const avatar = req.file ? `images/uploads/${req.file.filename}` : "";
  let sql = `update blog_user set avatar="${avatar}" where id = ${id}`;
  try {
    const [rows] = await db.promise().query(sql);
  } catch (error) {
    res.send(info(1, "数据库执行错误", debug ? error : ""));
  }
  sql = `select id,username,avatar from blog_user where id=${id}`;
  const [result] = await db.promise().query(sql);
  if (result) {
    res.send(info(0, "更新头像成功", result[0]));
  }
};
/**
 * 获取所有用户信息
 */
exports.getUsers = async (req, res) => {
  const { page = 1, size = 4, nickname } = req.query;
  // 计算偏移量
  const offset = (page - 1) * size;
  sql = `select * from blog_user limit ${offset},${size}`;
  const sql1 = `select * from blog_user where nickname like '%${nickname}%' limit ${offset},${size}`;
  if (nickname != "") {
    var [rows] = await db.promise().query(sql1);
    sql = `select count(*) as total from (${sql1}) middle_table`;
  } else {
    var [rows] = await db.promise().query(sql);
    sql = `select count(*) as total from blog_user`;
  }
  // 计算总数
  const [result] = await db.promise().query(sql);

  if (rows.length != 0 && result.length != 0) {
    var { total } = result[0];
    rows.forEach((item) => {
      delete item.password;
    });
    res.send(info(0, "获取所有成功", { total, rows }));
  } else {
    res.send(info(0, "暂无数据", []));
  }
};

/**
 * 获取单个用户信息
 */
exports.getSingle = async (req, res) => {
  const id = req.params.id;
  const sql = `select id,nickname,state,role from blog_user where id=${id}`;
  const [rows] = await db.promise().query(sql);
  if (rows.length != 0) {
    res.send(info(0, "获取指定用户信息成功", rows[0]));
  }
};

/**
 * 修改用户信息
 */
exports.updateInfo = async (req, res) => {
  const { id, nickname, state, role } = req.body;
  const sql = `update blog_user set nickname="${nickname}",state=${state},role="${role}" where id=${id}`;
  const [rows] = await db.promise().query(sql);
  if (rows.affectedRows == 1) {
    res.send(info(0, "修改信息成功", ""));
  }
};

/**
 * 删除用户
 */
exports.deleteUser = async (req, res) => {
  const { ids } = req.body;
  // console.log(ids);
  for (let i = 0; i < ids.length; i++) {
    let sql = `delete from blog_user where id=${ids[i]}`;
    var [rows] = await db.promise().query(sql);
  }
  res.send(info(0, "删除用户成功", ""));
};
